

package murcielago.player;

import java.io.IOException;
import java.io.InputStream;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;

/**
 *
 * @author Administrador
 */
class PlayerThread extends Thread {

    private LinkedQueue queue;
    boolean begin;

    public PlayerThread(LinkedQueue queue) throws IOException, MediaException{
        this.queue = queue;
        begin = true;
        createPlayers();
        preparePLayers();
    }

    private void createPlayers() throws IOException, MediaException{
        InputStream is;
        String element;
        for (int i=0; i<queue.size(); i++){
            element =(String)queue.poll();
            is = getClass().getResourceAsStream("/"+element+".mp3");
            queue.offer(Manager.createPlayer(is, "audio/mpeg"));
        }
    }

    public void run(){
        Player p=null;
        while ( (p = (Player) queue.poll()) != null){
            try {
                p.setMediaTime(5);
                if (!begin) {
                    p.setMediaTime(0);
                    begin = false;
                }
                p.start();
            } catch (MediaException ex) {
                ex.printStackTrace();
            }
        }
        begin = false;
    }

    private void preparePLayers() throws MediaException {
        for (int i=0; i<queue.size(); i++){
            Player p = (Player) queue.poll();
            p.realize();
            p.prefetch();
            queue.offer(p);
        }
    }
}
